<template>
    <div class="container">
        <van-nav-bar  fixed title="确认订单" left-arrow @click-left="onNavBack" />
 
         <!-- 收货信息 -->
        <van-cell-group inset >
        <van-cell
        :title="userInfo.receiverName || '未设置'"
        :value="userInfo.receiverPhone || '收货地址'"
        :label="userInfo.region + ' ' + userInfo.detailAddress"
        is-link
        @click="editAddress"
      />

        </van-cell-group>

        <!-- 商品信息 -->
        <van-cell-group inset class="product-info">
        <van-cell  class="product-detail"
            v-for="(item, index) in cartItems"
            :key="index"
            clickable
            
            >
            <template #icon>
                <div class="icon-container">
                <van-image 
                :src="item.productImage"
                class="image" 
                fit="cover"
                />
                </div>
            </template>

            <template #title>
                <div class="product-title">
                    {{ item.productName }}
                </div>
                <div class="product-desc">
                   规格: {{ item.spec }}（{{ item.deliveryDesc }}）
                </div>
                <div class="price">¥{{ item.price?.toFixed(2) }}</div>
            </template>

            <template #value>
                
                <div class="quantity">
                <van-stepper
                    v-model="item.quantity"
                    @change="handleStepperChange(item)"
                    input-width="32"
                    button-size="24"
                />
                </div>
            </template>

        </van-cell>
        </van-cell-group>

        <!-- 配送方式 -->
        <van-cell-group inset class="delivery">
          <van-cell title="配送方式" :value="deliveryMethod" is-link @click="chooseDelivery" />
        </van-cell-group>

        <!-- 支付方式 -->
        <van-cell-group inset class="pay">
          <van-cell title="支付方式" :value="paymentMethodText" is-link @click="choosePayment" />
        </van-cell-group>

        <!-- 优惠券 -->
        <van-cell-group inset class="coupon">
          <van-cell title="优惠券" :value="couponText" is-link @click="chooseCoupon" />
        </van-cell-group>

        <!-- 合计信息 -->
        <div class="total-bar">
          <div class="total-info-wrap">
          <div class="total-info">
           共{{ totalQuantity }}件,合计 
          </div>
          <div class="total-info-price">
            ¥ {{ totalAmount?.toFixed(2) }}
          </div>
          </div>  
        <van-button class="submit-btn"  @click="submitOrder">
           提交订单
        </van-button>
        </div>

  </div>
</template>

<script setup name="CheckOrder">
import { ref, computed ,onMounted} from 'vue';
import { useRouter ,useRoute} from 'vue-router';
import { showToast,showDialog  } from 'vant';
import {getOrder,queryAddresstByUid} from '../api/index';
import {useUserInfoStore}  from '../stores/userInfo'
import { useOrderStore } from '../stores/order';

const orderStore = useOrderStore();
const router = useRouter();

const route = useRoute(); 

const userInfoStore= useUserInfoStore();

const userId = userInfoStore.userId

// 商品信息
const cartItems = ref([]);

const userInfo = ref({
  receiverName: '', // 收件人姓名
  receiverPhone: '', // 手机号
  region: '', // 行政区域
  detailAddress: '', // 详细地址
  id: null // 地址ID（用于后续提交订单）
});


// 配送方式
const deliveryMethod = ref('快递包邮');

// 支付方式
const paymentMethod = ref('wechat'); // 标识：wechat/alipay等
const paymentMethodText = computed(() => {
  return paymentMethod.value === 'wechat' ? '微信支付' : '支付宝支付';
});

// 优惠券
const couponText = ref('暂无可用优惠券');

// 计算合计
const totalQuantity = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.quantity, 0);
});

const totalAmount = computed(() => {
  return cartItems.value.reduce(
    (sum, item) => sum + item.price * item.quantity,
    0
  );
});

// 返回上一页
const onNavBack = () => {
   //从cartItems中获取商品ID（cartItems是确认订单页的商品列表）
   orderStore.clearCartItems();
  const productId = cartItems.value[0]?.productId; 
  if (!productId) {
    showToast('未找到商品ID');
    return;
  }
  // 携带productId作为路由参数跳转
  router.push({
    name: "productDetail",
    query: { id: productId } // 传递商品ID到详情页
  });
};

// 编辑收货地址（可跳转到地址编辑页）
const editAddress = () => {
   router.push('/address');
};


// 数量加减回调
const handleStepperChange = (item) => {
  console.log('商品数量变化：', item);
};

// 选择配送方式
const chooseDelivery = () => {
  showDialog({ title: '选择配送方式', message: '当前仅支持快递包邮' });
};

// 选择支付方式
const choosePayment = () => {
  showDialog({
    title: '选择支付方式',
    message: '支持微信支付',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    async confirm() {
      paymentMethod.value = 'wechat'; 
    },
  });
};

// 选择优惠券
const chooseCoupon = () => {
  showToast('跳转到优惠券选择页');
};

// 提交订单
const submitOrder = async (info) => {

    const ree = await userInfoStore.getInfo()
    console.log("aaa",ree);

  try {
   
    const orderParams = {
      userId:   userId, // 实际需替换为当前登录用户ID（从token或缓存取）
      productId: cartItems.value[0].productId, 
      quantity: cartItems.value[0].quantity,
    }

    
    if (!cartItems.value.length) {
      return showToast('商品信息不存在');
    }
   
    const res = await getOrder(orderParams)

    
    if (!res) {
      return showToast('接口返回结果异常');
    }
  
    if (res.data) {
      showToast('订单创建成功，但无详情');
      return;
    }
       showToast('订单创建成功');
       orderStore.clearCartItems();
  } catch (error) {
    showToast('网络异常或服务器错误');
    console.error('提交订单失败：', error);
  }
};

// 订单页（CheckOrder）修改 onMounted
onMounted(async () => {
  loadDefaultAddress();
  
  // 1. 优先从路由参数获取本次传递的商品数据（关键修改）
  const productDataStr = route.query.productData;
  if (productDataStr) {
    try {
      const productData = JSON.parse(productDataStr);
      // 初始化商品列表
      cartItems.value = [
        {
          productId: productData.productId,
          productName: productData.productName,
          productImage: productData.imageUrl,
          spec: productData.spec,
          deliveryDesc: productData.deliveryDesc,
          price: productData.price,
          quantity: productData.quantity
        }
      ];
      // 强制更新状态管理，覆盖旧数据
      orderStore.setCartItems(cartItems.value);
      return; // 解析成功后，不再使用旧数据
    } catch (error) {
      console.error('解析商品数据失败:', error);
    }
  }

  // 2. 若路由参数解析失败，再 fallback 到状态管理数据（兼容异常场景）
  if (orderStore.cartItems.length > 0) {
    cartItems.value = orderStore.cartItems;
  } else {
    showToast('商品信息获取失败');
  }
});


//加载用户的默认地址
const loadDefaultAddress = async () => {
  try {
    // 调用接口获取用户的所有地址（假设用户ID为1，实际从登录信息获取）
    const addressList = await queryAddresstByUid(userId);

    if (addressList && addressList.length > 0) {
      // 筛选默认地址（isDefault === 1）
      const defaultAddress = addressList.find(addr => addr.isDefault === 1);
      
      if (defaultAddress) {
        // 填充默认地址信息
        userInfo.value = {
          id: defaultAddress.id,
          receiverName: defaultAddress.receiverName,
          receiverPhone: defaultAddress.receiverPhone,
          region: defaultAddress.region,
          detailAddress: defaultAddress.detailAddress
        };
      } else {
        // 无默认地址时，显示第一个地址
        const firstAddress = addressList[0];
        if (firstAddress) {
          userInfo.value = {
            id: firstAddress.id,
            receiverName: firstAddress.receiverName,
            receiverPhone: firstAddress.receiverPhone,
            region: firstAddress.region,
            detailAddress: firstAddress.detailAddress
          };
        } else {
          showToast('请先添加收货地址');
        }
      }
    } else {
      showToast('暂无收货地址，请添加');
    }
  } catch (error) {
    console.error('获取地址失败：', error);
    showToast('地址加载失败');
  }
};

</script>

<style lang='less' scoped>

.container {
  background-color: #f5f5f5; 
  min-height: 100vh; 
  padding-top: 55px; 
  padding-bottom: 50px; 
}

.product-info{
    margin-top: 10px;
}

.delivery{
    margin-top: 10px;
    height: 50px;
    padding: 5px;
}

.pay{
    margin-top: 10px;
    height: 50px;
    padding: 5px;
}

.coupon{
    margin-top: 10px;
    height: 50px;
    padding: 5px;
}


.van-cell {
  padding: 10px;
}

.product-detail{
    height: 125px;
}

.icon-container {
  width: 80px; 
  display: flex;
  justify-content: flex-start; 
}
.image {
  width: 65px;
  height: 65px;
  margin-top: 20px; 
}

.product-title {
  font-size: 15px;
  font-weight: bold;
  line-height: 1.2;
  margin-top: 10px;
}
.product-desc {
  font-size: 12px;
  color: #b9b7b7;
  margin-top: 5px;
}
.price {
  color: #f44336;
  font-size: 14px;
}
.quantity {
  display: flex;
  align-items: center;
  margin-top: 40px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-right: 10px;
}
.total-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  
}
.total-info-wrap {
  display: flex;
  margin-left: 80px;
}
.total-info {
  font-size: 13px;
  color: #080808;
   margin-top: 3px; 
}
.total-info-price {
  color: #2e2e2e;
  font-size: 20px;
  font-weight: bold;
  margin-left: 8px; 
}
.submit-btn {
  width: 120px;
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  border-radius: 30px;
  background-color: #FFD700;
  font-weight: bold;
 
}
</style>